package com.ftg.learn.assess.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.assess.client.CourseClient;
import com.ftg.learn.assess.client.StartClient;
import com.ftg.learn.assess.dto.AddAdminPageQueryDto;
import com.ftg.learn.assess.dto.UserAddAssessDto;
import com.ftg.learn.assess.dto.UserAdditionalDto;
import com.ftg.learn.assess.entity.Additional;
import com.ftg.learn.assess.entity.Assess;
import com.ftg.learn.assess.entity.Media;
import com.ftg.learn.assess.mappper.AdditionalMapper;
import com.ftg.learn.assess.result.PageResult;
import com.ftg.learn.assess.result.Result;
import com.ftg.learn.assess.service.AdditionalService;
import com.ftg.learn.assess.service.AssessService;
import com.ftg.learn.assess.service.MediaService;
import com.ftg.learn.assess.vo.CourseVo;
import feign.FeignException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class AdditionalServiceImpl extends ServiceImpl<AdditionalMapper,Additional> implements AdditionalService {
    @Autowired
    private MediaService mediaService;
    @Autowired
    private AssessService assessService;
    @Autowired
    private StartClient startClient;
    @Autowired
    private CourseClient courseClient;
    private static final String TAG = "NEGATIVE";
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> assess(UserAddAssessDto addAssessDto) {
        //判断该商品是否开启了自动回复公能
        Long productId = addAssessDto.getProductId();
        CourseVo courseVo = courseClient.getOne(productId).getData();
        Integer reply = courseVo.getReply();
        //调用ai返回自动回复的内容

        String message = addAssessDto.getContent();
        String sentiment=startClient.sentiment(message);
        log.info("ai审核后:{}",sentiment);
        Assess assess=BeanUtil.copyProperties(addAssessDto, Assess.class);
        if(sentiment.equals(TAG)){
            log.info("评价状设为隐藏");
            assess.setStatus(2);
            assess.setHideReason("依据ai筛选后,该用户评价已被隐藏");
        }
        assessService.save(assess);
        Long evaluationId = assess.getEvaluationId();
        if(evaluationId!=null){
            Optional.ofNullable(addAssessDto.getUrls()).ifPresent(urls -> {
                List<Integer> types = addAssessDto.getTypes();
                for (int i = 0; i < urls.size(); i++) {
                    Media m = new Media();
                    m.setMediaUrl(urls.get(i));
                    m.setMediaType(types != null && types.size() > i ? types.get(i) : null);
                    m.setEvaluationId(evaluationId);
                    mediaService.save(m);
                }
            });
        }
        if(reply==0){
            String result=startClient.reply(message);
            log.info("ai自动回复:{}",result);
            return Result.build(200, "success",result);
        }
        return Result.build(200, "success");
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> addAdditional(UserAdditionalDto userAdditionalDto) {
            Additional additional=BeanUtil.copyProperties(userAdditionalDto,Additional.class);
            this.baseMapper.insert(additional);
            if(additional.getAdditionalId()==null){
                return Result.build(500, "追评失败");
            }
//            if(additional.getAdditionalId()!=null){
//                List<String> urls = userAdditionalDto.getUrls();
//                List<Integer> types = userAdditionalDto.getTypes();
//                for (int i = 0; i < urls.size(); i++) {
//                    Media m = new Media();
//                    m.setMediaUrl(urls.get(i));
//                    m.setMediaType(types.get(i));
//                    m.setEvaluationId(userAdditionalDto.getEvaluationId());
//                    boolean save = mediaService.save(m);
//                    if(!save){
//                        return Result.build(500,"追评失败");
//                    }
//                }
//            }

            return Result.build(200,"追评成功");
    }

    @Override
    public Result<PageResult> pageQuery(AddAdminPageQueryDto queryDto) {
        Page<Additional> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        LambdaQueryWrapper<Additional> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery
                .like(StringUtils.hasText(queryDto.getContent()), Additional::getContent, queryDto.getContent())
                .eq(queryDto.getRating() != 0, Additional::getRating, queryDto.getRating())
                .eq(queryDto.getStatus() != 0, Additional::getStatus, queryDto.getStatus())
                .eq(queryDto.getEvaluationId() != 0, Additional::getEvaluationId, queryDto.getEvaluationId());
        Page<Additional> additionalPage = this.baseMapper.selectPage(page, lambdaQuery);
        if(additionalPage.getTotal() == 0){
            return Result.build(200, "分页查询成功，无数据", new PageResult(0, null));
        }
        return Result.build(200, "分页查询成功", new PageResult(additionalPage.getTotal(), additionalPage.getRecords()));
    }

    @Override
    public Result<List<Additional>> getAdditionalsByEvaluationId(Long evaluationId) {
        LambdaQueryWrapper<Additional> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Additional::getEvaluationId, evaluationId);
        List<Additional> additionals = this.baseMapper.selectList(queryWrapper);
        return Result.build(200, "查询成功", additionals);
    }

    @Override
    public Result<List<Additional>> MyPageageQuery(Long evaluationId) {
        LambdaQueryWrapper<Additional> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper
                .eq(evaluationId!=null,Additional::getEvaluationId,evaluationId);
        return Result.build(200, "查询成功", this.baseMapper.selectList(queryWrapper));
    }

}
